package com.example.manager.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.example.manager.service.ValidateCodeService;
import com.example.model.constant.RedisConstant;
import com.example.model.vo.system.ValidateCodeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //验证码图片的前缀
    public static final String IMAGE_PREFIX = "data:image/png;base64,";

    @Override
    public ValidateCodeVo generateValidateCode() {

        ValidateCodeVo validateCodeVo = new ValidateCodeVo();

        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 2);
        //1.通过工具（hutool）生成验证码
        // 4位验证码
        String code = circleCaptcha.getCode();

        //图片
        String imageBase64 = circleCaptcha.getImageBase64();

        String redisKey = UUID.randomUUID().toString().replaceAll("_", "");

        //2、把验证码存储到redis里面，设置redis的key: redis的value: 验证码的值
        redisTemplate.opsForValue().set(RedisConstant.USER_VALIDATE + redisKey, code, 5, TimeUnit.MINUTES);

        //3、返回ValidateCodeVo
        validateCodeVo.setCodeKey(redisKey);

        validateCodeVo.setCodeValue(IMAGE_PREFIX + imageBase64);

        return validateCodeVo;
    }
}
